#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author          : ricsy
@File            : js_compiler.py
@Create Time     : 2025/6/16 19:49
@Last Modified   :
@Description     :
"""
import subprocess

from src.settings import logger, project_root
from utils.environment_check import EnvironmentChecker


class JSCompiler:
    def __init__(self, debug):
        self.debug = debug
        self.webpack_config = project_root / "webpack.config.js"
        self.webpack_path = EnvironmentChecker().get_executable_path("webpack")
        logger.info(f"[JS] webpack 执行路径: {self.webpack_path}", 2)

    def build(self):
        cmd = [self.webpack_path, "--config", str(self.webpack_config)]
        if not self.debug:
            cmd.extend(["--mode=production", "--env", "production"])

        try:
            result = subprocess.run(
                cmd,
                cwd=project_root,
                check=True,
                capture_output=True,
                text=True,
                encoding="utf-8",
            )
            # 无论成功与否都记录输出
            logger.info(f"[JS] webpack stdout: {result.stdout}")
            if result.stderr:
                logger.error(f"[JS] webpack stderr:\n{result.stderr}")
            result.check_returncode()  # 主动触发异常
        except subprocess.CalledProcessError as e:
            logger.error(
                f"[JS] webpack 构建失败！完整错误:\n"
                f"命令: {e.cmd}\n"
                f"退出码: {e.returncode}\n"
                f"输出: {e.stdout}\n"
                f"错误: {e.stderr}"
            )
            raise

        return result.stdout


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="JS 编译工具")
    parser.add_argument("--debug", action="store_true", help="启用调试模式")
    args = parser.parse_args()

    builder = JSCompiler(args.debug)
    builder.build()
